import { defineStore } from "pinia";
import { reactive } from "vue";
import router, { constantRoutes, dynamicRoutes } from '@/router';
import { $getRouters } from "@/apis/user/user";
import to from "await-to-js";
import Layout from "@/Layout/Layout";
import ParentView from '@/components/ParentView/index.vue';
import auth from '@/common/plugins/auth';
export const useStore = defineStore('router', () => {
  const state: any = reactive({
    pulled: false,
    routes: [],
    addRoutes: [],
    defaultRoutes: [],
    topbarRouters: [],
    sidebarRouters: []
  })

  // 遍历后台传来的路由字符串，转换为组件对象
  const filterAsyncRouter = (asyncRouterMap, lastRouter = false, type = false) => {
    return asyncRouterMap.filter(route => {
      // if (type && route.children) {
      //   route.children = filterChildren(route.children)
      // }
      if (route.component) {
        // Layout ParentView 组件特殊处理
        if (route.component === 'Layout') {
          route.component = Layout;
        } else if (route.component === 'ParentView') {
          route.component = ParentView;
        } else {
          route.component = loadView(route.component);
        }
      }
      if (route.children != null && route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children, route, type)
      } else {
        delete route['children']
        delete route['redirect']
      }
      return true
    })
  }

  const filterChildren = (childrenMap, lastRouter?: any) => {
    let children: any[] = [];
    childrenMap.forEach((el, index) => {
      if (el.children && el.children.length) {
        if (el.component === 'ParentView' && !lastRouter) {
          el.children.forEach(c => {
            c.path = el.path + '/' + c.path
            if (c.children && c.children.length) {
              children = children.concat(filterChildren(c.children, c))
              return
            }
            children.push(c)
          })
          return
        }
      }
      if (lastRouter) {
        el.path = lastRouter.path + '/' + el.path
        if (el.children && el.children.length) {
          children = children.concat(filterChildren(el.children, el))
          return
        }
      }
      children = children.concat(el)
    })
    console.log(children)
    return children
  }

  const SET_ROUTES = (routes) => {
    state.addRoutes = routes;
    state.routes = constantRoutes.concat(routes);
  }
  const SET_DEFAULT_ROUTES = (routes) => {
    state.defaultRoutes = constantRoutes.concat(routes);
  }
  const SET_TOPBAR_ROUTES = (routes) => {
    state.topbarRouters = routes;
  }
  const SET_SIDEBAR_ROUTERS = (routes) => {
    state.sidebarRouters = routes;
  }

  // 拉取动态路由
  const GenerateRoutes = async () => {
    const [err, res]: any = await to($getRouters());
    const sdata = JSON.parse(JSON.stringify(res.data.data));
    const rdata = JSON.parse(JSON.stringify(res.data.data));
    const sidebarRoutes = filterAsyncRouter(sdata);
    const rewriteRoutes = filterAsyncRouter(rdata, false, true);
    const asyncRoutes = filterDynamicRoutes(dynamicRoutes);
    rewriteRoutes.push({ path: '/:pathMatch(.*)*', redirect: '/404', hidden: true });
    asyncRoutes.forEach(x => {
      router.addRoute(x);
    })
    SET_ROUTES(rewriteRoutes);
    SET_SIDEBAR_ROUTERS(constantRoutes.concat(sidebarRoutes));
    SET_DEFAULT_ROUTES(sidebarRoutes);
    SET_TOPBAR_ROUTES(sidebarRoutes);
    return rewriteRoutes;
  }
  return {
    state,
    GenerateRoutes,
  }
})

export const loadView = (view) => {
  return () => import(`@/views/${view}`);
}

// 动态路由遍历，验证是否具备权限
export function filterDynamicRoutes(routes) {
  const res: any[] = [];
  routes.forEach(route => {
    if (route.permissions) {
      if (auth.hasPermiOr(route.permissions)) {
        res.push(route)
      }
    } else if (route.roles) {
      if (auth.hasRoleOr(route.roles)) {
        res.push(route)
      }
    }
  })
  return res
}